package com.qyer.search.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * User: Z J Wu Date: 2016/02/16 Time: 14:58 Package: com.qyer.search.utils
 */
public class BatchResultCollector {

  private static final Logger LOGGER = LoggerFactory.getLogger(BatchResultCollector.class);

  public static final String HOST = "rukawa-test.qyer.com";
  public static final int PORT = 80;
  public static final String PATH = "/bs/search";

  private static HttpClient client;

  static {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    int totalConnection = 100, apiResponseConnection = totalConnection;
    cm.setMaxTotal(totalConnection);
    cm.setDefaultMaxPerRoute(apiResponseConnection);
    HttpHost responseServer = new HttpHost(HOST, PORT);
    cm.setMaxPerRoute(new HttpRoute(responseServer), apiResponseConnection);
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(5000).setConnectionRequestTimeout(5000);
    client = HttpClients.custom().setConnectionManager(cm)
                        .setDefaultRequestConfig(requestBuilder.build()).build();
  }

  public static String doHttp(final String s) throws URISyntaxException, IOException {
    String kw = StringUtils.trimToNull(s);
    if (StringUtils.isBlank(kw)) {
      return null;
    }
    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(HOST);
    builder.setPort(PORT);
    builder.setPath(PATH);
    builder.addParameter("only_data", String.valueOf(true));
    builder.addParameter("simple", String.valueOf(true));
    builder.addParameter("context", "test");
    builder.addParameter("kw", s);
    URI uri = builder.build();
    LOGGER.info(URLDecoder.decode(uri.toString(), "utf-8"));
    HttpGet get = new HttpGet(builder.build());
    HttpResponse httpResponse;
    StatusLine statusLine;
    HttpEntity responseEntity;
    try {
      httpResponse = client.execute(get);
      if (httpResponse == null) {
        return null;
      }
      statusLine = httpResponse.getStatusLine();
      if (statusLine.getStatusCode() != 200) {
        return null;
      }
      responseEntity = httpResponse.getEntity();
      return IOUtils.toString(responseEntity.getContent(), Charsets.toCharset("utf8"));
    } finally {
      get.releaseConnection();
    }
  }

  public static void main(String[] args) throws IOException, URISyntaxException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> resultMap, dataMap;
    List<Map<String, Object>> dataList;
    //String s = "/Users/WuZijing/securecrt_rzsz/keyword3-9", content;
    String s = "/Users/tangzheng/Documents/tangTool/misc/search_key/2016-3-15kw", content;
    Path in = Paths.get(s);
    Path out = Paths.get(s + ".out");
    try (BufferedReader br = Files
      .newBufferedReader(in, Charset.forName("utf8")); BufferedWriter bw = Files
      .newBufferedWriter(out, Charset.forName("utf8"))) {
      String line, response;
      while ((line = br.readLine()) != null) {
        line = StringUtils.trimToNull(line);
        if (StringUtils.isBlank(line)) {
          continue;
        }
        bw.write(line);
        bw.write('\t');
        response = doHttp(line);
        resultMap = mapper.readValue(response, Map.class);
        if (MapUtils.isEmpty(resultMap)) {
          bw.write(String.valueOf(0));
          bw.write('\t');
          continue;
        }
        int total = 0;
        int status = Integer.parseInt(resultMap.get("status").toString());
        if (status == 0) {
          dataMap = (Map<String, Object>) resultMap.get("data");
          if (MapUtils.isEmpty(dataMap)) {
            content = "";
          } else {
            dataList = (List<Map<String, Object>>) dataMap.get("content");
            if (CollectionUtils.isEmpty(dataList)) {
              content = "";
            } else {
              for (Map<String, Object> skuMap : dataList) {
                total += (int) skuMap.get("skus_size");
              }
              content = response;
            }
          }
        } else {
          content = "";
        }
        bw.write(String.valueOf(total));
        bw.write('\t');
        bw.write(content);
        bw.write('\n');
      }
    }
  }
}
